//
//  BabyCircleViewController.m
//  MyDemo
//
//  Created by ci123 on 15-3-5.
//  Copyright (c) 2015年 ci123nbg. All rights reserved.
//

#import "BabyCircleViewController.h"
#import "CellStyleClassCircle.h"
#import "MJRefresh.h"
#import "NetWorkManager.h"
#import "BDKNotifyHUD.h"
#import "UserDao.h"
#import "PopUIManager.h"
#import "JsonUtil.h"
#import "UIImageView+WebCache.h"
#import "SMViewController.h"
#import "PostViewController.h"
#import "DetailNewViewController.h"
#import "JoinClassViewController.h"
#import "CityViewController.h"
#import "AFAppClient.h"
#import "ForumViewCell.h"
#import "ForumViewController.h"
#import "ChooseForumViewController.h"
#import "Config.h"
#import "MyloginViewController.h"
#import "HomeItemViewCell.h"
#import "UMSocial.h"
#import "ChatViewController.h"

@interface BabyCircleViewController ()<MWPhotoBrowserDelegate>

@property  UIButton *baby_btn;
@property  UIButton *much_btn;

@property UIView *headerView;
@property NSUInteger selected_index;

@property UIView *selected_line;

@property NSMutableArray *baby_data;
@property NSArray *much_data;
@property NSArray *data;

@property BDKNotifyHUD *hud;

@property NSString *avatar_header;

@property UIView *notips;

@property BOOL is_first ;
@property (weak, nonatomic) IBOutlet UIButton *pubButton;

@property MWPhotoBrowser *browser;

@property NSUInteger currentIndex;

@end

@implementation BabyCircleViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //_quan_data = [[NSMutableArray alloc]init];
    _baby_data = [[NSMutableArray alloc]init];
    _much_data = @[@{@"type":@(1),@"image":@"文化养老2",@"title":@"文化养老",@"content":@"张扬你的个性 积极享受快乐"},
                   @{@"type":@(2),@"image":@"智慧生活2",@"title":@"智慧生活",@"content":@"依托云端服务 物联创新生活"},
                   @{@"type":@(3),@"image":@"健康养生2",@"title":@"健康养生",@"content":@"一手养生资讯 潮流健康生活"},
                   @{@"type":@(4),@"image":@"时尚汇2",@"title":@"时尚汇",@"content":@"时尚JOJO 坐镇聊穿衣"}];
    /*,
                   @{@"type":@(5),@"image":@"云律师2",@"title":@"云律师",@"content":@"世界律师平台 全球各地贴身保护"}*/
                   
    _data = @[@{@"type":@(1),@"image":@"文化养老",@"title":@"来自文化养老",@"content":@"张扬你的个性 积极享受快乐",@"color":RGBACOLOR(254,199,8, 1)},
              @{@"type":@(2),@"image":@"智慧生活",@"title":@"来自智慧生活",@"content":@"依托云端服务 物联创新生活",@"color":RGBACOLOR(252,130,7, 1)},
              @{@"type":@(3),@"image":@"健康养生",@"title":@"来自健康养生",@"content":@"一手养生资讯 潮流健康生活",@"color":RGBACOLOR(123,209,4, 1)},
              @{@"type":@(4),@"image":@"时尚汇",@"title":@"来自时尚汇",@"content":@"时尚JOJO 坐镇聊穿衣",@"color":RGBACOLOR(252,108,173, 1)},
              @{@"type":@(5),@"image":@"云律师",@"title":@"来自云律师",@"content":@"世界律师平台 全球各地贴身保护",@"color":RGBACOLOR(25,197,241, 1)}
              ];
    //_tableview.delegate = self;
    //_tableview.dataSource = self;
    
    _tableview2.delegate = self;
    _tableview2.dataSource = self;
    
    _tableview3.delegate = self;
    _tableview3.dataSource = self;
    
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, APP_SCREEN_WIDTH, 104)];
    [imageView setImage:[UIImage imageNamed:@"top_bar"]];
    _tableview3.tableHeaderView = imageView;
    
    _selected_index = 1;
    [self customView];
    [self setUpRefreshPlugin];
    
//    [self initNoTips];
//    if([[UserDao getInstance]getCurrentBaby].classid==0){
//        self.navigationItem.rightBarButtonItem.enabled = NO;
//    }
    _is_first = YES;
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    if(_is_first){
        _is_first = NO;
        [self.tableview2 headerBeginRefreshing];
        [self.view bringSubviewToFront:_tableview2];
        [self.view bringSubviewToFront:_pubButton];
    }else{
        if(_selected_index==1){
            [_tableview2 headerBeginRefreshing];
        }else if(_selected_index == 2){
           // [_tableview3 headerBeginRefreshing];
        }
    }
}

-(void)initNoTips
{
    _notips = [[UIView alloc]initWithFrame:CGRectMake(0, 100, APP_SCREEN_WIDTH, 100)];
    UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake((APP_SCREEN_WIDTH-120)/2, 0, 120, 15)];
    label1.textColor = UIColorMake(45, 45, 45);
    label1.text = @"你还没有班级动态";
    label1.font = [UIFont systemFontOfSize:15];
    label1.textAlignment = NSTextAlignmentCenter;
    [_notips addSubview:label1];
    
    UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake((APP_SCREEN_WIDTH-260)/2, 20, 260, 15)];
    label2.textColor = UIColorMake(180, 180, 180);
    label2.text = @"赶紧加入班级就可以看到动态啦！";
    label2.font = [UIFont systemFontOfSize:15];
    label2.textAlignment = NSTextAlignmentCenter;
    [_notips addSubview:label2];
    
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake((APP_SCREEN_WIDTH-120)/2, 50, 100, 30)];
    [button setTitle:@"加入班级" forState:UIControlStateNormal];
    [button setTintColor:[UIColor whiteColor]];
    [button setBackgroundColor:UIColorMake(252, 74, 74)];
    [button addTarget:self action:@selector(addClass:) forControlEvents:UIControlEventTouchUpInside];
    button.layer.cornerRadius = 3.0;
    [_notips addSubview:button];
    [self.view addSubview:_notips];
    _notips.hidden = YES;
}
-(void)addClass:(id)sender
{
    JoinClassViewController *joinClass = [[JoinClassViewController alloc]init];
    BabyInfo *baby = [[UserDao getInstance]getCurrentBaby];
    joinClass.babyid = baby.cid;
    [self.navigationController pushViewController:joinClass animated:YES];
}

/**
 *  集成刷新控件
 */
- (void)setUpRefreshPlugin
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
//[_tableview addHeaderWithTarget:self action:@selector(headerRereshing)];
    [_tableview2 addHeaderWithTarget:self action:@selector(headerRereshing)];
   // [_tableview3 addHeaderWithTarget:self action:@selector(headerRereshing)];
    //#warning 自动刷新(一进入程序就下拉刷新)
   // [_tableview headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
   // [_tableview addFooterWithTarget:self action:@selector(footerRereshing)];
    [_tableview2 addFooterWithTarget:self action:@selector(footerRereshing)];
  //  [_tableview3 addFooterWithTarget:self action:@selector(footerRereshing)];
    
    //设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
//    _tableview.headerPullToRefreshText = @"下拉刷新";
//    _tableview.headerReleaseToRefreshText = @"松开刷新";
//    _tableview.headerRefreshingText = @"正在刷新...";
//    
//    _tableview.footerPullToRefreshText = @"上拉加载";
//    _tableview.footerReleaseToRefreshText = @"松开加载";
//    _tableview.footerRefreshingText = @"正在加载...";
    
    _tableview2.headerPullToRefreshText = @"下拉刷新";
    _tableview2.headerReleaseToRefreshText = @"松开刷新";
    _tableview2.headerRefreshingText = @"正在刷新...";
    
    _tableview2.footerPullToRefreshText = @"上拉加载";
    _tableview2.footerReleaseToRefreshText = @"松开加载";
    _tableview2.footerRefreshingText = @"正在加载...";
    
    /*
    _tableview3.headerPullToRefreshText = @"下拉刷新";
    _tableview3.headerReleaseToRefreshText = @"松开刷新";
    _tableview3.headerRefreshingText = @"正在刷新...";
    
    _tableview3.footerPullToRefreshText = @"上拉加载";
    _tableview3.footerReleaseToRefreshText = @"松开加载";
    _tableview3.footerRefreshingText = @"正在加载...";
     */
}

-(void)customView{
    
    self.navigationController.navigationBarHidden = NO;
   // self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
        self.edgesForExtendedLayout = UIRectEdgeNone;
   // self.navigationItem.title = @"话题";
    /*
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
                                initWithTitle:@""
                                   style:UIBarButtonItemStylePlain
                                   target:nil
                                   action:nil];
    self.navigationItem.backBarButtonItem=backButton;
    
    UIBarButtonItem *leftItem =[[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"left_menu"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(leftViewCallback:)];
    
    self.navigationItem.leftBarButtonItem = leftItem;
     */
    
    
    /*
    UIBarButtonItem *rightItem =[[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"pencil"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(rightItemClick:)];
    self.navigationItem.rightBarButtonItem = rightItem;
     */
    
    
    _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 170, 45)];
    
    [_headerView setBackgroundColor:[UIColor clearColor]];
    
    _much_btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 5, 85, 40)];
    [_much_btn setTitle:@"推荐" forState:UIControlStateNormal];
    _much_btn.titleLabel.font = [UIFont systemFontOfSize:20.0];
    
    [_much_btn addTarget:self action:@selector(childCareCallback:) forControlEvents:UIControlEventTouchUpInside];
    _baby_btn = [[UIButton alloc]initWithFrame:CGRectMake(85, 5, 85, 40)];
    [_baby_btn setTitle:@"莱吧" forState:UIControlStateNormal];
    [_baby_btn addTarget:self action:@selector(bigMixCallback:) forControlEvents:UIControlEventTouchUpInside];
    _baby_btn.titleLabel.font = [UIFont systemFontOfSize:20.0];
    
    [_headerView addSubview:_much_btn];
    [_headerView addSubview:_baby_btn];
    
    self.navigationItem.titleView = _headerView;
    
    [self setBtnsStatus];
    /*
    UIView *verticalLineView=[[UIView alloc] initWithFrame:CGRectMake(0, 40, 170, .8)];
    [verticalLineView setBackgroundColor:UIColorMake(220, 220, 220)];
    [_headerView addSubview:verticalLineView];
     */
    
    _selected_line = [[UIView alloc]initWithFrame:CGRectMake(20.5, 38, 44, 0.5)];
    [_selected_line setBackgroundColor:UIColorMake(252, 74, 74)];
    [_headerView addSubview:_selected_line];
    
    _hud = [[BDKNotifyHUD alloc]initWithImage:[UIImage imageNamed:@"Star"] text:@"哎呦~您的网络有问题，请查看网络设置"];
    _hud.center = CGPointMake(APP_SCREEN_WIDTH/2, APP_SCREEN_WIDTH/2 );
    [self.view addSubview:_hud];
    //[self.view bringSubviewToFront:_tableview];
}

//================顶部刷新，获取最新动态=========================
//首次进入会自动执行一次获取最新动态
- (void)headerRereshing
{
    if ([NetWorkManager connectedToNetwork]) {
            [self getArticles:@"new" withBaseid:0];
        }else{
        //没有网络的情况下，加载本地缓存数据
        [_hud presentWithDuration:1.0f speed:0.5f inView:self.view completion:^{
            [_hud removeFromSuperview];
        }];
       
    }
}
/*
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if(tableView == _tableview3){
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, APP_SCREEN_WIDTH, 104)];
        [imageView setImage:[UIImage imageNamed:@"top_bar"]];
        return imageView;
    }else{
        return nil;
    }
}
 */
//================底部刷新，获取更多班级圈=========================
- (void)footerRereshing
{
    if([NetWorkManager connectedToNetwork]) {
        NSDictionary *lastObject;
        if(_selected_index==1){
            lastObject = [_baby_data lastObject];
        }else if(_selected_index == 2){
            lastObject = [_much_data lastObject];
        }
        [self getArticles:@"old" withBaseid:[[lastObject objectForKey:@"id"]integerValue]];
        
    }else{
        [_hud presentWithDuration:1.0f speed:0.5f inView:self.view completion:^{
            [_hud removeFromSuperview];
        }];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}
/*
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(tableView == _tableview3){
        return 104;
    }else{
        return 0.01f;
    }
}*/

-(void)getArticles:(NSString*)requestType withBaseid:(NSUInteger)baseid
{
    //NSString* uid = [NSString stringWithFormat:@"%ld",[[UserDao getInstance] getUserId]];
    //NSString* utype = @"1";
    NSUInteger is_rec= 0;
    if(_selected_index == 1){
        is_rec = 1;
    }
    NSDictionary *temp_dict = [[NSDictionary alloc]initWithObjectsAndKeys:@(0),@"posttype",requestType,@"dir",@(baseid), @"baseid",@(is_rec),@"is_rec", nil];
    
 
    PopUIManager *popUIMgr = [PopUIManager getInstanse];
    [popUIMgr showWaitingUI:self.view];
    
    [[AFAppClient sharedManager]getWithURL:[NSString stringWithFormat:@"%@%@",SERVER_URL_NEW,API_USER_GET_ARTICLES] withParameters:temp_dict success:^(NSDictionary *dict) {
        [popUIMgr removeWaitingUI];
        if ([requestType isEqualToString:@"new"]) {
            if(_selected_index==1){
                [self.tableview2 headerEndRefreshing];
            }else if(_selected_index ==2){
                //[self.tableview3 headerEndRefreshing];
            }
            
        }else if ([requestType isEqualToString:@"old"]){
            if(_selected_index==1){
                [self.tableview2 footerEndRefreshing];
            }else if(_selected_index ==2){
               // [self.tableview3 footerEndRefreshing];
            }
        }
        if ([[dict objectForKey:@"ret"] integerValue]== 1) {
            NSUInteger retCode = [[dict objectForKey:@"retCode"] integerValue];
            switch (retCode) {
                case 1:
                {
                    _avatar_header = [dict objectForKey:@"avatar_header"];
                    if ([requestType isEqualToString:@"new"]) { //下拉 获取最新数据的回调
                        if(_selected_index==1){
                            [_baby_data removeAllObjects];
                            
                        }else if(_selected_index ==2){
                            
                           // [_much_data  removeAllObjects];
                        }
                    }
                    NSArray *posts = [dict objectForKey:@"posts"];
                    if(_selected_index==1){
                        for (NSDictionary *item in posts) {
                            [_baby_data addObject:item];
                        }
                        [_tableview2 reloadData];
                    }else if(_selected_index ==2){
                       /* for (NSDictionary *item in posts) {
                            [_much_data addObject:item];
                        }
                        [_tableview3 reloadData];
                        */
                    }
                    
                    break;
                }
                case 10020:
                {
                    [_hud setImage:[UIImage imageNamed:@"Checkmark"]];
                    [_hud setText:@"没有更多数据了"];
                    [_hud presentWithDuration:1.0 speed:.5 inView:self.view completion:^{
                        
                    }];
                    break;
                }
                    
                default:
                    break;
            }
            
        }else{
            [popUIMgr popAlertView:nil title:@"提示" message:@"数据解析错误" cancelButtonTitle:@"确定"];
        }
    } failure:^(NSError *error) {
        [popUIMgr removeWaitingUI];
        if ([requestType isEqualToString:@"new"]) {
            if(_selected_index==1){
                [self.tableview2 headerEndRefreshing];
            }else if(_selected_index ==2){
               // [self.tableview3 headerEndRefreshing];
            }
            
        }else if ([requestType isEqualToString:@"old"]){
            if(_selected_index==1){
                [self.tableview2 footerEndRefreshing];
            }else if(_selected_index ==2){
               // [self.tableview3 footerEndRefreshing];
            }
        }
        [popUIMgr popAlertView:nil title:@"提示" message:@"网络连接出错" cancelButtonTitle:@"确定"];
    }];

}


-(void)setBtnsStatus
{
    switch (_selected_index) {
        case 1:
        {
            //[_quan_btn setTitleColor:UIColorMake(252, 74, 74) forState:UIControlStateNormal];
            [_much_btn setTitleColor:UIColorMake(252, 74, 74) forState:UIControlStateNormal];
            [_baby_btn setTitleColor:UIColorMake(91, 91, 91) forState:UIControlStateNormal];
            [_selected_line setFrame:CGRectMake(20.5, 38, 44, .5)];

            break;
        }
        case 2:
        {
            [_much_btn setTitleColor:UIColorMake(91, 91, 91) forState:UIControlStateNormal];
           // [_quan_btn setTitleColor:UIColorMake(91, 91, 91) forState:UIControlStateNormal];
            [_baby_btn setTitleColor:UIColorMake(252, 74, 74) forState:UIControlStateNormal];
            [_selected_line setFrame:CGRectMake(106, 38, 44, .5)];
             self.navigationItem.rightBarButtonItem.enabled = YES;
            break;
        }
            default:
            break;
    }
}

-(void)leftViewCallback:(id)sender{
   // [[SMViewController sharedSMViewController]showLeftView:YES];
    CityViewController *cityView = [[CityViewController alloc]init];
    [self.navigationController pushViewController:cityView animated:YES];
}
- (IBAction)pubAction:(id)sender {
    if([[Config Instance]isCookie]){
        ChooseForumViewController *forum = [[ChooseForumViewController alloc]init];
        forum.circle = self;
        [forum setModalPresentationStyle:UIModalPresentationCurrentContext];
        UIWindow *window = [[UIApplication sharedApplication]keyWindow];
        forum.view.frame = window.bounds;
        [forum showInView:window animated:YES];
        [self addChildViewController:forum];
        [forum didMoveToParentViewController:self];
    }else{
        MyloginViewController *login = [MyloginViewController shareController];
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:login];
        [self presentViewController:nav animated:YES completion:^{
            
        }];
    }
    
}
-(void)pubIn:(NSUInteger)type
{
    
    PostViewController *postView  = [[PostViewController alloc]init];
    postView.postType = [NSString stringWithFormat:@"%ld",type];
    UINavigationController *post_nav = [[UINavigationController alloc]initWithRootViewController:postView];
    [self presentViewController:post_nav animated:YES completion:^{
        
    }];
}

-(void)rightItemClick:(id)sender{
    PostViewController *postView  = [[PostViewController alloc]init];
    postView.postType = [NSString stringWithFormat:@"%ld",(unsigned long)_selected_index];
    UINavigationController *post_nav = [[UINavigationController alloc]initWithRootViewController:postView];
    [self presentViewController:post_nav animated:YES completion:^{
        
    }];
}



- (IBAction)childCareCallback:(id)sender {
    if(_selected_index ==1){
        return;
    }
    _selected_index =1;
    [self setBtnsStatus];
    [self.tableview2 headerBeginRefreshing];
    [self.view bringSubviewToFront:_tableview2];
    [self.view bringSubviewToFront:_pubButton];
}
- (IBAction)bigMixCallback:(id)sender {
    if(_selected_index ==2){
        return;
    }
    _selected_index =2;
    [self setBtnsStatus];
    //[self.tableview3 headerBeginRefreshing];
    [self.view bringSubviewToFront:_tableview3];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(tableView == _tableview2){
        /*
        static NSString *CellIdentifier = @"CellStyleClassCircle";
        CellStyleClassCircle *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            NSArray *nibArr = [[NSBundle mainBundle]loadNibNamed:@"CellStyleClassCircle" owner:self options:nil];
            cell = (CellStyleClassCircle *)[nibArr objectAtIndex:0];
            [cell setAccessoryType:UITableViewCellAccessoryNone];
        }
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        NSDictionary *article;
        article = [_baby_data objectAtIndex:indexPath.row];
        
        
        NSString *avatar =[article objectForKey:@"author_avatar"];
        [cell.avatar sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",_avatar_header,avatar]] placeholderImage:[UIImage imageNamed:@"default_circle_icon"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
        }];
        cell.avatar.layer.cornerRadius = 20;
        cell.avatar.layer.masksToBounds = YES;
        
        NSString *title = [article objectForKey:@"title"];
        cell.title.text = title;
        
        NSString *post_time = [article objectForKey:@"post_time"];
        cell.time.text = post_time;
        
        NSString *relpynum = [article objectForKey:@"replynum"];
        cell.replyNum.text = [NSString stringWithFormat:@"%@",relpynum];
        
        NSString *transfernum = [article objectForKey:@"transfernum"];
        cell.transferNum.text = [NSString stringWithFormat:@"%@",transfernum];
        
        NSString *goodnum = [article objectForKey:@"goodnum"];
        cell.goodNum.text = [NSString stringWithFormat:@"%@",goodnum];
        
        NSString *author_name = [article objectForKey:@"content"];
        cell.author.text = author_name;
         */
        static NSString *CellIdentifier = @"HomeItemViewCell";
        HomeItemViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            @try{
                NSArray *nibArr = [[NSBundle mainBundle]loadNibNamed:@"HomeItemViewCell" owner:self options:nil];
                cell = (HomeItemViewCell *)[nibArr objectAtIndex:0];
            }
            @catch(NSException *exception) {
                NSLog(@"exception:%@", exception);
            }
            @finally {
                
            }
            //        cell = [[HomeItemViewCell alloc]init];
            [cell setAccessoryType:UITableViewCellAccessoryNone];
        }
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        NSDictionary *article;
        article = [_baby_data objectAtIndex:indexPath.row];
        
        NSUInteger type = [[article objectForKey:@"type"]integerValue];
        for (NSDictionary *dict in _data) {
            if(type == [[dict objectForKey:@"type"]integerValue]){
                //cell.forumIcon.image = [UIImage imageNamed:[dict objectForKey:@"image"]];
                cell.forumTitle.text = [dict objectForKey:@"title"];
                cell.forumTitle.textColor = [dict objectForKey:@"color"];
                break;
            }
        }
        NSString *avatar =[article objectForKey:@"author_avatar"];
        [cell.avatar sd_setImageWithURL:[NSURL URLWithString:avatar] placeholderImage:[UIImage imageNamed:@"default_circle_icon"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        }];
        cell.avatar.layer.cornerRadius = 16.5;
        cell.avatar.layer.masksToBounds = YES;
        
        cell.avatar.userInteractionEnabled = YES;
        cell.avatar.tag = indexPath.row;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(chatView:)];
        [cell.avatar addGestureRecognizer:tap];
        
        NSString *author_name = [article objectForKey:@"author_name"];
        [cell.author setText:author_name];
        
        NSString *title = [article objectForKey:@"title"];
        cell.title.text = title;
        
        NSString *post_time = [article objectForKey:@"new_post_time"];
        cell.time.text = post_time;
        
        NSString *relpynum = [article objectForKey:@"replynum"];
        cell.replyNum.text = [NSString stringWithFormat:@"%@",relpynum];
        
        // NSString *transfernum = [article objectForKey:@"transfernum"];
        // cell.transferNum.text = [NSString stringWithFormat:@"%@",transfernum];
        
        NSString *goodnum = [article objectForKey:@"goodnum"];
        cell.goodNum.text = [NSString stringWithFormat:@"%@",goodnum];
        
        NSString *city = [article objectForKey:@"author_city"];
        cell.city.text = city;
        
        NSString *sex =[NSString stringWithFormat:@"%@", [article objectForKey:@"author_sex"]];
        
        if([sex isEqualToString:@"1"]){
            cell.sexImg.image = [UIImage imageNamed:@"man"];
        }else{
            cell.sexImg.image = [UIImage imageNamed:@"woman"];
        }

        
        NSArray *pics = [article objectForKey:@"pics"];
        int imageTag = 100 * indexPath.row;
        if(pics&& [pics count]>0){
            //        [cell.picsView setHidden:NO];
            //        [cell.picsView setFrame:CGRectMake(10, 87, 300, 83)];
            cell.picViewHight.constant = 80 + (80+6)*(([pics count]-1)/3);
            NSArray *subviews = [cell.picsView subviews];
            for (UIView *v in subviews) {
                [v removeFromSuperview];
            }
            for (NSUInteger i=0; i<[pics count]; i++) {
                NSString *ul = [pics objectAtIndex:i];
                NSUInteger pic_width = 80;
                UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(i%3*(pic_width+6), ((i/3)*(pic_width+6)), pic_width, pic_width)];
                [image setContentMode:UIViewContentModeScaleAspectFill];
                image.userInteractionEnabled = YES;
                UITapGestureRecognizer *ges=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showImages:)];
                [image addGestureRecognizer:ges];
                image.tag = imageTag;
                imageTag++;

                image.clipsToBounds  = YES;
                [image sd_setImageWithURL:[NSURL URLWithString:ul] placeholderImage:nil];
                [cell.picsView addSubview:image];
            }
        }else{
            //        [cell.picsView setHidden:YES];
            cell.picViewHight.constant = 0;
        }
        
        cell.shareView.userInteractionEnabled = YES;
        UITapGestureRecognizer *gest = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickShare:)];
        [cell.shareView addGestureRecognizer:gest];
        
        cell.goodView.userInteractionEnabled = YES;
        UITapGestureRecognizer *gest1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(goods:)];
        [cell.goodView addGestureRecognizer:gest1];
        cell.goodView.tag =[[article objectForKey:@"id"]integerValue];
        
        return cell;
    }else{
        static NSString *CellIdentifier1 = @"ForumClassCircle";
        ForumViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
        if (cell == nil) {
            NSArray *nibArr = [[NSBundle mainBundle]loadNibNamed:@"ForumViewCell" owner:self options:nil];
            cell = (ForumViewCell *)[nibArr objectAtIndex:0];
            [cell setAccessoryType:UITableViewCellAccessoryNone];
        }
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        NSDictionary *dict = [_much_data objectAtIndex:indexPath.row];
        
        cell.iconImg.image = [UIImage imageNamed:[dict objectForKey:@"image"]];
        
        cell.title.text = [dict objectForKey:@"title"];
        cell.content.text = [dict objectForKey:@"content"];
        return cell;
    }
}

-(void)chatView:(UITapGestureRecognizer*)rec
{
    UIView *view = [rec view];
    NSUInteger tag = [view tag];
    NSDictionary *article = [_baby_data objectAtIndex:tag];
    
    ChatViewController *chatVC = [[ChatViewController alloc] initWithChatter:[article objectForKey:@"author_id"] isGroup:NO];
    //            chatVC.title = [[UserProfileManager sharedInstance] getNickNameWithUsername:buddy.username];
    chatVC.title = [article objectForKey:@"author_name"];
    chatVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:chatVC animated:YES];
}

-(void)goods:(UITapGestureRecognizer*)sender
{
    if([[Config Instance]isCookie]){
        UIView *view = [sender view];
        NSUInteger tag = [view tag];
        if(tag>0){
            PopUIManager *popUIMgr = [PopUIManager getInstanse];
            [popUIMgr showWaitingUI:self.view];
            [[AFAppClient sharedManager]getWithURL:[NSString stringWithFormat:@"%@%@",SERVER_URL_NEW,kUserPostGood] withParameters:@{@"uid":@([[Config Instance]getUID]),@"pid":@(tag)} success:^(NSDictionary *responseObject) {
                [popUIMgr removeWaitingUI];
                [_tableview2 headerBeginRefreshing];
            } failure:^(NSError *error) {
                [popUIMgr removeWaitingUI];
            }];
        }else{
            
        }
        
    }else{
        
        MyloginViewController *login = [MyloginViewController shareController];
        
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:login];
        [self presentViewController:nav animated:YES completion:^{
            
        }];
        
    }
}
-(void)clickShare:(id)sender
{
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"55a73f3a67e58e7b700001c9"
                                      shareText:@"阿莱回家，国内最大的中老年人线上交流平台，www.zgyxyl.com"
                                     shareImage:[UIImage imageNamed:@"share_icon"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToWechatTimeline,UMShareToWechatSession,UMShareToQQ,UMShareToQzone,nil]
                                       delegate:self];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%@",indexPath);
    //该方法响应列表中行的点击事件
    NSInteger row = indexPath.row;
    NSDictionary *dict;
    if(tableView == _tableview2){
       
        if(_selected_index == 1){
            dict = [_baby_data objectAtIndex:row];
        }else if(_selected_index == 2){
            dict = [_much_data objectAtIndex:row];
        }else{
            
        }
        NSUInteger pid = [[dict objectForKey:@"id"]integerValue ];
        DetailNewViewController *detail = [[DetailNewViewController alloc]init];
        detail.msgId = [NSString stringWithFormat:@"%ld",pid];
        detail.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:detail animated:YES];
    }else{
        dict = [_much_data objectAtIndex:row];
        NSUInteger type = [[dict objectForKey:@"type"]integerValue];
        ForumViewController *forum = [[ForumViewController alloc]init];
        forum.type = type;
        forum.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:forum animated:YES];
    }
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([tableView isEqual:_tableview2]) {
        return _baby_data.count;
    }else if ([tableView isEqual:_tableview3]){
        return _much_data.count;
    }else{
        return 0;
    }
}

//设置Cell行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(tableView==_tableview2){
        return [self getHeightByIndex:indexPath.row];
    }else{
        return 68;
    }
}

-(NSUInteger)getHeightByIndex:(NSUInteger)index
{
    NSDictionary *article;
    article = [_baby_data objectAtIndex:index];
    NSArray *pics = [article objectForKey:@"pics"];
    if(pics&& [pics count]>0){
        NSUInteger length = [pics count];
        return 134+80 + (80+6)*((length-1)/3) ;
    }else{
        return 134;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)showImages:(UITapGestureRecognizer *)tap{
    UIView *view = [tap view];
    NSUInteger index = view.tag/100;
    
    _currentIndex = index;
    
    NSInteger i = view.tag % 100;
    
    // if(_browser == nil) {
    _browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    _browser.displayActionButton = NO;
    _browser.displayNavArrows = YES;
    _browser.enableGrid = NO;
    // }
    
    [_browser setCurrentPhotoIndex:i];
    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:_browser];
    nc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:nc animated:YES completion:nil];
}

#pragma mark - MWPhotoBrowserDelegate
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    NSDictionary *article = [_baby_data objectAtIndex:_currentIndex];
    NSArray *pics = [article objectForKey:@"pics"];
    return pics.count;
}

- (MWPhoto *)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    NSDictionary *article = [_baby_data objectAtIndex:_currentIndex];
    NSArray *pics = [article objectForKey:@"pics"];
    if (index < pics.count)
        return [MWPhoto photoWithURL:[NSURL URLWithString:[pics objectAtIndex:index]]];
    return nil;
}

- (MWPhoto *)photoBrowser:(MWPhotoBrowser *)photoBrowser thumbPhotoAtIndex:(NSUInteger)index {
    NSDictionary *article = [_baby_data objectAtIndex:_currentIndex];
    NSArray *pics = [article objectForKey:@"pics"];
    if (index < pics.count)
        return [MWPhoto photoWithURL:[NSURL URLWithString:[pics objectAtIndex:index]]];
    return nil;
}

@end
